// Copyright (c) 2010 god6or@gmail.com under MIT license.

package ul

import collection.mutable.{ListBuffer}

object str {

    // replaces non-ascii bytes with decimal escapes
    def esc( bytes: Array[Byte] ): Array[Byte] = {
        val out = new ListBuffer[Byte]
        for ( b <- bytes ) {
            var bi:Int = if (b < 0) 256 + b.toInt else b
            if ((bi <= 32) || (bi == 92)) { //|| (bi >= 126) ) {
                out += 92 // slash + DEC code
                out += (bi / 100 + 48).toByte; bi = bi - (bi / 100 * 100)
                out += (bi / 10 + 48).toByte; bi = bi - (bi / 10 * 10)
                out += (bi + 48).toByte
            } else out += b;
        }
        return out.toArray
    }

    // replaces decimal escapes with bytes
    def unesc( bytes: Array[Byte] ): Array[Byte] = {
        val out = new ListBuffer[Byte]
        var i = 0
        while ( i < bytes.length ) {
            val b = bytes(i)
            var bi:Int = if (b < 0) 256 + b.toInt else b
            
            if (bi == 92) {
                out += ((bytes(i+1)-48).toInt * 100 + (bytes(i+2)-48).toInt * 10 + (bytes(i+3)-48).toInt).toByte
                i += 4
            } else {
                out += b
                i += 1
            }
        }
        return out.toArray
    }

}

